import socket
import threading


class Server:
    def __init__(self):
        self.ip = socket.gethostbyname(socket.gethostname())
        self.port = 9809
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connections = []
        self.running = False

        print("Server created")

    def start(self):
        try:
            self.s.bind((self.ip, self.port))
            self.s.listen(100)
            print('Running on IP: ' + self.ip)
            print('Running on port: ' + str(self.port))
            self.running = True
            self.accept_connections()
        except Exception as e:
            print("Couldn't bind to the port:", e)

    def accept_connections(self):
        while self.running:
            c, addr = self.s.accept()
            self.connections.append(c)
            threading.Thread(target=self.handle_client, args=(c, addr)).start()

    def broadcast(self, sock, data):
        for client in self.connections:
            if client != sock:
                try:
                    client.send(data)
                except:
                    pass

    def handle_client(self, c, addr):
        while self.running:
            try:
                data = c.recv(1024)
                if not data:
                    break
                # print(data)
                self.broadcast(c, data)
            except socket.error:
                break

        c.close()

    def stop(self):
        self.running = False
        self.s.close()
        for c in self.connections:
            c.close()

